

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.util.List;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Tomasz
 */
public class content_driven_GUI {
    public List allNodes;
     JTree jTree2;
    List fields;
    List buttons;
    JTextArea ta;
    JFrame f;
    xml_tree_manipulator x;
    public content_driven_GUI() throws FileNotFoundException, IOException
    {
     x = new xml_tree_manipulator();
        JFileChooser fc = new JFileChooser();
        xmlFilter xf = new xmlFilter();
        fc.setFileFilter(xf);
        int returnVal = fc.showOpenDialog(f);
        fc.setCurrentDirectory(new File(System.getProperty("user.home")));
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
             
          
       BufferedReader reader = new BufferedReader(new FileReader(file));
       String line;
       
           while ((line = reader.readLine()) != null)
    {
     
    }

           
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;Element root = null;
try{
    

Document doc = null;
                try {   
                    dBuilder = dbFactory.newDocumentBuilder();try {
                        doc = dBuilder.parse(file);
                    } catch (SAXException ex) {
                        Logger.getLogger(MyJApplet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(MyJApplet.class.getName()).log(Level.SEVERE, null, ex);
                }

doc.getDocumentElement().normalize();
 root = doc.getDocumentElement();  
}
catch (Exception e)
        {
            MessageBox m = new MessageBox("Błąd w pliku XML");
return;
        }

 NodeList nodes = root.getChildNodes();
 allNodes = new ArrayList()
 {

                    @Override
                    public int indexOf(Object o) {
                        //return super.indexOf(o);
                        try
                        {
                        for (int i =0;i<this.size()-1;i++)
                        {
                            if (((xml_node_container)allNodes.get(i)).node.getNodeName() == ((xml_node_container)o).node.getNodeName()) {
                                return i;
                            }
                        }}
                        catch (Exception e)
                        {
                            return -1;
                        }
                        return -1;
                    }
                    
                    
     
 };
 
  allNodes.add(new xml_node_container(root, 0));

 
 jTree2 = new JTree();
  DefaultMutableTreeNode r = (DefaultMutableTreeNode) jTree2.getModel().getRoot();
 r.setUserObject(root.getNodeName());
 r.removeAllChildren();
  int depth = 1;
  int t = nodes.getLength();
 for (int i = 1; i<t;i+=1)
 {

      int temp = 0;
      String tempo = nodes.item(i).getNodeName();
      if (tempo == "#text") continue;
    // String tempVal = nodes.item(i).getNodeValue();
  //    temp = allNodes_contains(new xml_node_container(nodes.item(i),depth));
      temp = allNodes.indexOf(new xml_node_container(nodes.item(i),depth));
    //  boolean check = (temp > -1 && ((xml_node_container)allNodes.get(temp)).node.getParentNode().getNodeName().equals(nodes.item(i).getParentNode().getNodeName()));
  if (temp > -1)
  {
      ((xml_node_container)allNodes.get(temp)).setIs_multinode();
      continue;
  } 
  
  r.add(new DefaultMutableTreeNode(nodes.item(i).getNodeName()));
     if (x.ma_dzieci(nodes.item(i))) {
        allNodes.add(new xml_node_container(nodes.item(i), depth,true));  
     }
       
     else{
        allNodes.add(new xml_node_container(nodes.item(i), depth));
     }

     if (x.ma_dzieci(nodes.item(i)))
     {
          NodeList test = nodes.item(i).getChildNodes();
           Node test2 = nodes.item(i).getFirstChild();
            x.addChildstoNode(nodes.item(i).getChildNodes(),(DefaultMutableTreeNode)r.getLastChild(), ++depth,allNodes);

     }
     
 }    
    f = new JFrame("Wygenreowany formularz") ;
    
  //  Container content = f.getContentPane();
    JPanel content = new JPanel(); 
    JScrollPane jsp = new JScrollPane(content);
    f.add(jsp);
    content.setBackground(Color.white);
    content.setLayout(new GridLayout(0,3));
    //JTree j = new JTree(l.get(0));
      fields = new ArrayList();
     buttons = new ArrayList();
    Boolean is_in_form = false;

    
   f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
  //f.setsize
  // f.add(jTree2);
   boolean bylo = false;
   int test = allNodes.size();
  
   for (int i = 1;i<allNodes.size();i++)
   {

       JLabel templabel = new JLabel(((xml_node_container)allNodes.get(i)).node.getNodeName());
       JTextField tf = new JTextField();
       
      
       tf.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               int containerIdx=-1;
               
                for (int i=0;i<fields.size();i++)
                   {
                       if (fields.get(i).equals(e.getSource()))
                       {
                           containerIdx = i;
                           break;
                       }
                   }
                int nodeIdx = containerIdx +1;
            String t = "<"+((xml_node_container)allNodes.get(nodeIdx)).node.getNodeName() + ">"+((JTextField)fields.get(containerIdx)).getText() + "</"+((xml_node_container)allNodes.get(nodeIdx)).node.getNodeName() + ">\n";
               int wciecie =  ((xml_node_container)allNodes.get(nodeIdx)).depth;
                         for (int i = 0;i<wciecie;i++) {
                               t="\t"+t;
                           }
               
               ((JTextField)fields.get(containerIdx)).setToolTipText(t);
               ((JTextField)fields.get(containerIdx)).setBackground(Color.decode("#8fc400"));
           }
       });
       
       
      
       boolean testVis = ((xml_node_container)allNodes.get(i)).is_just_parrent;
       tf.setVisible(!((xml_node_container)allNodes.get(i)).is_just_parrent);
       JButton butt = new JButton("Dodaj");
       boolean isMultonode = ((xml_node_container)allNodes.get(i)).is_multinode;
       butt.setVisible(((xml_node_container)allNodes.get(i)).is_multinode);
       butt.setToolTipText("");
       butt.addActionListener(new ActionListener() {

               @Override
               public void actionPerformed(ActionEvent e) {
                  int containerIndex =-1;
                   for (int i=0;i<buttons.size();i++)
                   {
                       if (buttons.get(i).equals(e.getSource()))
                       {
                           containerIndex = i;
                           break;
                       }
                   }
                  // temp++; //TUTAJ MUSI BYC PLUS JEDEN BO BUTTONY LICZYMY OD 0 A ELEMENTY TAK NAPRAWDE OD 1 BO 0 TO JEST ROOT
                       int childContainerIndex = containerIndex+1;
                       int nodeIndex = containerIndex +1;
                       int childNodeIndex = nodeIndex+1;
                       
                       if (((xml_node_container)allNodes.get(nodeIndex)).node.getNodeType() == Node.TEXT_NODE)
                       {
                          
                           String dodaj = "";
                            int wciecie =  ((xml_node_container)allNodes.get(nodeIndex)).depth;
                         for (int i = 0;i<wciecie;i++) {
                               dodaj+="\t";
                           }
                
                          dodaj += ((JTextField)fields.get(containerIndex)).getToolTipText();
                        
                          ((JButton)buttons.get(containerIndex)).setToolTipText(((JButton)buttons.get(containerIndex)).getToolTipText()+dodaj);
                       ((JTextField)fields.get(containerIndex)).setText(null);
                       ((JTextField)fields.get(containerIndex)).setToolTipText(null);
                       ((JTextField)fields.get(containerIndex)).setBackground(Color.white );
                       
                       
                       }
                       else
                       {
                             String dodaj ="";
                              int wciecie =  ((xml_node_container)allNodes.get(nodeIndex)).depth;
                         for (int i = 0;i<wciecie;i++) {
                               dodaj+="\t";
                           }
                          
                           dodaj += "<"+((xml_node_container)allNodes.get(nodeIndex)).node.getNodeName()+">\n";
                     //      ta.setText(ta.getText().replace(replace_me, dodaj + replace_me));
                                   
                   try{
                       while (((xml_node_container)allNodes.get(nodeIndex)).depth < ((xml_node_container)allNodes.get(childNodeIndex)).depth)
                       {  
                           int wciecie3 =  ((xml_node_container)allNodes.get(childNodeIndex)).depth;
                         for (int i = 0;i<wciecie3;i++) {
                               dodaj+="\t";
                           }
                          try{
                              
                               
                               
                          
                           dodaj += "<"+((xml_node_container)allNodes.get(childNodeIndex)).node.getNodeName()+">" + ((JTextField)fields.get(childContainerIndex)).getText()+"</"+((xml_node_container)allNodes.get(childNodeIndex)).node.getNodeName()+">\n\r";
                        //   ta.setText(ta.getText().replace(replace_me, dodaj+replace_me));
                           ((JTextField)fields.get(childContainerIndex)).setBackground(Color.white);
                           ((JTextField)fields.get(childContainerIndex)).setText(null);
                           ((JTextField)fields.get(childContainerIndex)).setToolTipText(null);
                           
                           
                          }
                          catch (Exception exc)
                                  {
                                   break;
                                  }
                           childContainerIndex++;
                           childNodeIndex++;
                       }
                   }
                     catch (Exception exc)
                                  {
                                  //OutOfArray
                                  }
                             int wciecie4 =  ((xml_node_container)allNodes.get(nodeIndex)).depth;
                         for (int i = 0;i<wciecie4;i++) {
                               dodaj+="\t";
                           }    
                           dodaj += "</"+((xml_node_container)allNodes.get(nodeIndex)).node.getNodeName()+">\n";
                          // ta.setText(ta.getText().replace(replace_me, dodaj + replace_me));
                         
                           ((JButton)buttons.get(containerIndex)).setToolTipText(((JButton)buttons.get(containerIndex)).getToolTipText()+dodaj);
                       }
                       
                   
                   
                   
               }
               
           });
  
     
       content.add(templabel);
       content.add(tf);
       fields.add(tf);
       butt.setText(null);
       buttons.add(butt);
      
       content.add(butt);
       
       butt = null;
       tf = null;
       templabel = null;
   }

      ta = new JTextArea("<"+((xml_node_container)allNodes.get(0)).node.getNodeName() +">\n\r"+"\n</"+((xml_node_container)allNodes.get(0)).node.getNodeName()+">");
    
    JButton gap = new JButton();
    gap.setVisible(false);
    content.add(gap);
    gap = null;
    gap = new JButton();
    gap.setVisible(false);
    content.add(gap);
    JButton refr;
            refr = new JButton("Odświerz");
    refr.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                      ta.setText("<" + ((xml_node_container)allNodes.get(0)).node.getNodeName() + ">\n");
                        
                        String dodaj="";
                      
                      for (int i = 0; i < fields.size();i++)
                      {
                          if (((JButton)buttons.get(i)).getToolTipText() != "")
                          {
                              String t = ((JButton)buttons.get(i)).getToolTipText();
                               dodaj+= ((JButton)buttons.get(i)).getToolTipText();
                          }
                             
                          else
                          {
                          if (((JTextField)fields.get(i)).getToolTipText() != null) {
                                  dodaj += ((JTextField)fields.get(i)).getToolTipText();
                              }
                          }
                      }
                      ta.setText(ta.getText()+ dodaj + "</" + ((xml_node_container)allNodes.get(0)).node.getNodeName() + ">");
                    }
                });
    
    
    refr.setSize(100, 100);
        content.add(refr);
    
      content.add(new JLabel("Podgląd pliku"));
   
     content.add(ta);
     JButton zapis = new JButton("Zapisz");
     zapis.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                            JFileChooser fc = new JFileChooser();
                            xmlFilter xf = new xmlFilter();
        fc.setFileFilter(xf);
        int returnVal = fc.showSaveDialog(f);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
                   file = new File(file.getPath()+".xml");
            //This is where a real application would save the file.
            BufferedWriter bw;
            try {
                bw = new BufferedWriter(new FileWriter(file));
                bw.write(ta.getText());
                bw.flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else {
        }
                    }
                });
     content.add(zapis);
     f.setSize(600, 800);
    f.setVisible(true);
    }
    
    }
}
